//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Configuration;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;

namespace CommunityServer.Galleries.Controls
{
	public class QuickAddPhoto : TemplatedWebControl
	{
		#region Child Controls

		private HtmlInputFile PictureData;
		private IButton Submit;
		private RegularExpressionValidator AttachmentDataValidator;

		#endregion

		private string categories =  "";

		public bool HasCategories
		{
			get { return (categories.Length > 0); }
		}

		protected override string ThemeName
		{
			get
			{
				return "default";
			}
		}
        
		/// <summary>
		/// A comma seperated list of categories / tags to add the post to
		/// </summary>
		public string Categories
		{
			get { return categories; }
			set { categories = value; }
		}

		private string requiredRoles = "";
        
		/// <summary>
		/// If set, this overrides the required permissions to add a photo
		/// </summary>
		public string RequiredRoles
		{
			get { return requiredRoles; }
			set { requiredRoles = value; }
		}

		public bool HasRequiredRoles
		{
			get { return (requiredRoles.Length > 0); }
		}

		private bool makeApproved = true;
		/// <summary>
		/// Create the new post in an approved state or moderate it
		/// </summary>
		public bool MakeApproved
		{
			get { return makeApproved; }
			set { makeApproved = value; }
		}

		private int sectionID = -1;
		/// <summary>
		/// The Gallery SectionID to load the photo into
		/// </summary>
		public int SectionID
		{
			get
			{
				if (sectionID < 0)
				{
					try
					{
						sectionID = CSContext.Current.GetIntFromQueryString("sectionid", sectionID);
					}
					catch { }
				}
				if (sectionID < 0)
				{
					try
					{
						sectionID = CSContext.Current.GetIntFromQueryString("galleryid", sectionID);
					}
					catch { }
				}
				if (sectionID < 0)
				{
					try
					{
						string appKey = CSContext.Current.ApplicationKey;
						if (!Globals.IsNullorEmpty(appKey))
						{
							Gallery g = Galleries.GetGallery(appKey);
							if (g != null)
								sectionID = g.SectionID; 
						}
					}
					catch { }
				}
              
				return sectionID;
			}
			set { sectionID = value; }
		}

		private bool autoPostBack = true;
		public bool AutoPostBack
		{
			get { return autoPostBack; }
			set { autoPostBack = value; }
		}

		public Gallery destinationGallery = null;
		public Gallery DestinationGallery
		{
			get
			{
				if (destinationGallery == null && this.SectionID > 0)
					destinationGallery = Galleries.GetGallery(this.SectionID);

				if (destinationGallery.SectionID != this.SectionID)
					destinationGallery = Galleries.GetGallery(this.SectionID);

				return destinationGallery;
			}
			set
			{
				destinationGallery = value;
				this.SectionID = value.SectionID;
			}
		}
		#region Skin

		protected override void AttachChildControls()
		{
			PictureData = (HtmlInputFile)FindControl("PictureData");
			AttachmentDataValidator = (RegularExpressionValidator)FindControl("AttachmentDataValidator");
			Submit = FindButton("Submit");
			InitializeChildControls();
		}

		private void InitializeChildControls()
		{
			AttachmentDataValidator.Text = ResourceManager.GetString("CP_Photos_Attachment_UploadAttachment_InvlalidFileType", "ControlPanelResources.xml");
			AttachmentSettings fs = GalleryConfiguration.Instance().AttachmentSettings;
			AttachmentDataValidator.ValidationExpression = fs.ValidationPattern;

			//Add some autopostback action to the quickadd
			//no validator PictureData.Attributes.Add("onchange","__doPostBack('" + PictureData.ClientID + "','');") ;
			//if(this.AutoPostBack)
			//        PictureData.Attributes.Add("onchange", "if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate()) __doPostBack('" + PictureData.ClientID + "','');");

			if (this.AutoPostBack)
				PictureData.Attributes.Add("onchange", Page.GetPostBackEventReference(PictureData));
            
			if(Submit != null)
				Submit.Click += new EventHandler(Submit_Click);
            
			if (Page.IsPostBack && this.AutoPostBack)
			{
				//check to see if our quick add has data
				if ((PictureData != null) && (PictureData.PostedFile != null) && (PictureData.PostedFile.ContentLength > 0))
					QuickAddPicture();

			}
            

		}

		#endregion
  
		#region Event Overrides

		protected override void OnLoad(EventArgs e)
		{
			this.EnsureChildControls();
			if(!Page.IsPostBack)
				Submit.Text = ResourceManager.GetString( "Add" );
		}

		protected override void OnPreRender(EventArgs e)
		{
			//Submit.Attributes.Add("onclick", "return SubmitSendToFriend('" + From.ClientID + "', '" + To.ClientID + "');");
		}

		#endregion

		#region Event Handlers

		private void Submit_Click(object sender, EventArgs e)
		{
			if((PictureData != null) && (PictureData.PostedFile != null) && (PictureData.PostedFile.ContentLength > 0))
				QuickAddPicture();
		}

		protected void Authorize()
		{
			//make sure the user is authenticated
			if (!CSContext.Current.IsAuthenticated)
				Page.Response.Redirect(Globals.GetSiteUrls().Login);

			//Required roles can be used in place of Post permission
			if (this.HasRequiredRoles)
			{
				if (!CSContext.Current.User.IsInRoles(this.RequiredRoles.Split(',')))
					PermissionBase.RedirectOrExcpetion(CSExceptionType.AccessDenied);
			}
			else
			{
				//the user needs to be the post owner or moderator or above to edit a post
				Permissions.AccessCheck(this.DestinationGallery, Permission.Post, CSContext.Current.User);
			}
		}
		#endregion

		private void QuickAddPicture()
		{
			Authorize();
            
			PostAttachment pa = new PostAttachment(PictureData.PostedFile);
			pa.SectionID = this.SectionID;
			GalleryPosts.CreatePicture(pa, this.MakeApproved, this.Categories) ;

			CSContext context = CSContext.Current;

			if (context.ReturnUrl != null && context.ReturnUrl.Length > 0)
				context.Context.Response.Redirect(context.ReturnUrl);
			else
				context.Context.Response.Redirect(Globals.AppendQuerystring(GalleryUrls.Instance().ControlPanel_Photos_PostList, String.Format("sectionid={0}", this.SectionID.ToString())));
		}
	}
}
